<template>
	<div class="top">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Classification">课程管理</a>
			</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Video">视频管理</a>
			</el-breadcrumb-item>
		</el-breadcrumb>
	</div>

	<div class="middel">
		<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
			<el-form-item label="视频名称">
				<el-input v-model="queryInfo.videoName" placeholder="请输入视频名称" clearable />
			</el-form-item>
      <el-form-item label="所属课程">  <!-- 加上label，和其他项对齐 -->
        <el-select
          v-model="queryInfo.courseId"
          placeholder="请选择课程"
          clearable
          style="width: 200px"
        >
          <el-option label="全部课程" value="" />
          <el-option
            v-for="course in courseOptions"
            :key="course.value"
            :label="course.label"
            :value="course.value"
          />
        </el-select>
      </el-form-item>
			<el-form-item>
				<el-button type="primary" @click="search">搜索</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="success" @click="openDialog('add')">新增视频</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="batchDelete" :disabled="multipleSelection.length === 0">
					批量删除
				</el-button>
			</el-form-item>
		</el-form>
	</div>

	<div class="content">
		<el-table
			ref="multipleTableRef"
			:data="tableData"
			row-key="id"
			style="width: 100%"
			@selection-change="handleSelectionChange"
			:loading="loading"
			border
			stripe
			class="category-table"
		>
			<el-table-column type="selection" width="55" />
			<el-table-column prop="id" label="视频ID" width="100" align="center" />
			<el-table-column prop="videoName" label="视频名称" min-width="180" align="center" show-overflow-tooltip />
      <el-table-column label="视频预览" width="200">
        <template #default="scope">
          <video
            width="180"
            height="100"
            controls
            :src="`${scope.row.videoUrl}`"
            style="object-fit: cover; border-radius: 4px"
          ></video>
        </template>
      </el-table-column>

      <el-table-column label="视频时长" width="120" align="center">
        <template #default="scope">
          {{ formatSecondsToTime(scope.row.videoTime) }}
        </template>
      </el-table-column>
			<el-table-column prop="course.courseName" label="所属课程" min-width="150" align="center" show-overflow-tooltip />

			<el-table-column label="操作" width="240" align="center">
				<template #default="scope">
					<div style="display: flex; justify-content: center; gap: 16px;">
						<el-button size="small" type="primary" @click="openDialog('edit', scope.row)">编辑</el-button>
						<el-button size="small" type="danger" @click="deleteVideo(scope.row.id)">删除</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="queryInfo.pageNum"
			:page-sizes="[5, 10, 15, 20]"
			:page-size="queryInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			style="margin-top: 20px"
		/>
	</div>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
		<el-form :model="form" label-width="110px" class="dialog-form">
			<el-form-item label="视频名称" required>
				<el-input v-model="form.videoName" autocomplete="off" maxlength="50" show-word-limit />
			</el-form-item>
      <el-form-item label="视频时长">
        <el-input
          :value="formatSecondsToTime(form.videoTime)"
          disabled
          clearable="false"
        />
      </el-form-item>


      <el-form-item label="视频上传">
        <el-upload
          class="video-uploader"
          :action="baseURL+'upload'"
          :show-file-list="false"
          accept="video/*"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        >
          <video
            v-if="form.videoUrl"
            :src="`${form.videoUrl}`"
            controls
            style="width: 300px; height: 170px; border-radius: 4px"
          ></video>
          <el-icon v-else><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="所属课程" required>
        <el-select v-model="form.courseId" placeholder="请选择课程" clearable>
          <el-option
            v-for="course in courseOptions"
            :key="course.value"
            :label="course.label"
            :value="course.value"
          />
        </el-select>
      </el-form-item>

    </el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus';
import http from '@/util/http';
	const baseURL = http.defaults.baseURL



// 查询参数
const queryInfo = reactive({
  id: '',
  videoName: '',
  courseId: '', // 改为存储课程ID
  pageSize: 10,
  pageNum: 1
});
const duration = reactive({
  hours: 0,
  minutes: 0,
  seconds: 0
});

// 表格数据和分页
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 选择相关
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<any[]>([]);

const axios = getCurrentInstance().appContext.config.globalProperties.axios;

// 弹窗表单
const dialogVisible = ref(false);
const dialogTitle = ref('新增视频');
const form = reactive({
  id: null,
  videoName: '',
  videoTime: 0,
  videoUrl: '',
  courseId: null,
  del: 0,
  course: null,
});

const dialogMode = ref("add");


// 查询列表
const queryDataList = () => {
	loading.value = true;
	axios.get('courseVideo/all', {
		params: queryInfo
	})
	.then((response) => {
		if (response && response.code === 200) {
			tableData.value = response.data.list || [];
			total.value = response.data.total || 0;
			// console.log('tableData.value:',tableData.value);
		} else {
			ElMessage.error(response.message || '查询失败');
		}
	})
	.catch(() => {
		ElMessage.error('网络请求错误，请检查网络连接或服务器状态');
	})
	.finally(() => {
		loading.value = false;
	});
};
const courseOptions = ref([]);

// 使用Promise链式调用获取课程列表
const loadCourses = () => {
  axios.get('course/all', {
    params: {
      pageNum: 1,        // 页码，从1开始
      pageSize: 100   // 每页条数，设置为100
    }
  })
    .then(resp => {
      console.log('课程列表响应:', resp);
      if (resp.code === 200) {
        courseOptions.value = resp.data.list.map(item => ({
          label: item.courseName,  // 显示的课程名称
          value: item.id             // 课程ID
        }));
        console.log('处理后的课程选项:', courseOptions.value);
      } else {
        throw new Error(`获取课程失败: ${resp.message || '未知错误'}`);
      }
    })
    .catch(error => {
      console.error('获取课程列表失败', error);
      ElMessage.error('获取课程列表失败，请稍后重试');
    });
};

onMounted(() => {
	queryDataList();
  loadCourses();
});

// 搜索
const search = () => {
	queryInfo.pageNum = 1;
	queryDataList();
};
function pad(num: number): string {
  return (num < 10 ? '0' : '') + num;
}


function formatSecondsToTime(seconds: number | string): string {
  const s = Number(seconds);
  const hrs = Math.floor(s / 3600);
  const mins = Math.floor((s % 3600) / 60);
  const secs = s % 60;

  return `${pad(hrs)}:${pad(mins)}:${pad(secs)}`;
}
// 视频上传
function beforeUpload(file) {
  const isVideo = file.type.startsWith('video/')
  if (!isVideo) {
    ElMessage.error('只能上传视频文件')
  }
  return isVideo
}

function handleUploadSuccess(response) {
  // 假设后端返回结构：{ code: 200, data: '/upload/xxxx.mp4' }
  if (response.code === 200) {
    form.videoUrl = response.data;
    ElMessage.success('视频上传成功');

    // 创建隐藏 video 元素，加载视频以获取时长
    const video = document.createElement('video');
    video.preload = 'metadata';
    video.src = `${form.videoUrl}`;

    video.onloadedmetadata = () => {
      const totalSeconds = Math.floor(video.duration);
      form.videoTime = totalSeconds;  // 自动设置视频时长，单位秒
      console.log('视频时长（秒）：', totalSeconds);
    };
  } else {
    ElMessage.error('上传失败');
  }
}


function handleUploadError() {
  ElMessage.error('上传错误，请重试')
}



// 分页
const handleSizeChange = (size: number) => {
	queryInfo.pageSize = size;
	queryDataList();
};
const handleCurrentChange = (num: number) => {
	queryInfo.pageNum = num;
	queryDataList();
};

// 选择
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};

// 打开弹窗
function openDialog(mode: 'add' | 'edit', row?: any) {
  dialogMode.value = mode;
  console.log(mode);

  if (mode === 'add') {
    dialogTitle.value = '新增视频';

    form.id = '';
    form.videoName = '';

    form.videoTime = '';

    form.courseId = '';
    form.videoImage = ''; // 清空图片字段
    form.videoUrl = '';
    // 新增时长下拉初始化
    duration.hours = 0;
    duration.minutes = 0;
    duration.seconds = 0;

    dialogVisible.value = true;

  } else if (mode === 'edit' && row) {
    dialogTitle.value = '编辑视频';

    // 直接从 row 设置数据
    form.id = row.id;
    form.videoName = row.videoName;
    form.videoTime = row.videoTime;
    form.videoUrl = row.videoUrl;      // 视频地址字段
    form.courseId = row.courseId;
    form.course = row.course || null;
    form.del = row.del ?? 0;

    // 设置时长
    const totalSeconds = Number(row.videoTime || 0);
    duration.hours = Math.floor(totalSeconds / 3600);
    duration.minutes = Math.floor((totalSeconds % 3600) / 60);
    duration.seconds = totalSeconds % 60;

    dialogVisible.value = true;
  }

}


// 上传相关
const uploadData = reactive({}) // 可根据需要传递额外参数



function submitForm() {
  if (!form.videoName.trim()) {
    ElMessage.warning('请输入视频名称');
    return;
  }

  // 这里用 form.videoTime 直接作为时长（单位秒）
  if (!form.videoTime || form.videoTime === 0) {
    ElMessage.warning('视频时长不能为空或为0');
    return;
  }

  if (!form.courseId) {
    ElMessage.warning('请输入课程ID');
    return;
  }

  const payload = {
    id: form.id,
    videoName: form.videoName,
    videoTime: form.videoTime,  // 改为直接用form.videoTime
    videoUrl: form.videoUrl,
    courseId: form.courseId
  };




  const request = dialogMode.value === 'add'
    ? axios.post('courseVideo', payload)
    : axios.put('courseVideo', payload);

  request.then((resp: any) => {
    if (resp.code === 200) {
      ElMessage.success(dialogMode.value === 'add' ? '新增成功' : '编辑成功');
      dialogVisible.value = false;
      queryDataList();
    } else {
      ElMessage.error(resp.message || `${dialogMode.value === 'add' ? '新增' : '编辑'}失败`);
    }
  });
}


// 删除
function deleteVideo(id: number) {
	ElMessageBox.confirm('确定要删除该视频吗？', '提示', {
		type: 'warning'
	}).then(() => {
		axios.delete(`courseVideo/${id}`).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('删除成功');
				queryDataList();
			} else {
				ElMessage.error(resp.message || '删除失败');
			}
		});
	});
}

// 批量删除
function batchDelete() {
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请选择要删除的视频');
		return;
	}
	ElMessageBox.confirm('确定要批量删除选中的视频吗？', '提示', {
		type: 'warning'
	}).then(() => {
		const ids = multipleSelection.value.map((item: any) => item.id);
    axios.delete('courseVideo', {
      params: {  ids: ids.join(',') }  // 发送为 ?ids=4,2
    }).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('批量删除成功');
				queryDataList();
			} else {
				ElMessage.error(resp.message || '批量删除失败');
			}
		});
	});
}
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'

const dialogImageUrl = ref('')
const disabled = ref(false)

const handleRemove = (file: UploadFile) => {
  console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}
</script>

<style scoped>
.top {
	background-color: #f8f9fa;
	padding: 12px 20px;
	margin-bottom: 15px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.el-breadcrumb {
	max-width: 1200px;
	margin: 0 auto;
}
.middel {
	background: #fff;
	padding: 20px;
	margin-bottom: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.demo-form-inline {
	display: flex;
	align-items: center;
	gap: 15px;
}
.demo-form-inline .el-form-item {
	margin-right: 20px;
}
.demo-form-inline .el-input,
.demo-form-inline .el-select {
	width: 220px;
}

.el-button + .el-button {
	margin-left: 10px;
}
.content {
	background: #fff;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.category-table {
	background: #fff;
	border-radius: 8px;
}
.el-table {
	margin-bottom: 20px;
}

.dialog-form {
	padding-top: 10px;
}
.avatar-uploader .avatar {
	width: 100px;
	height: 100px;
	display: block;
}
</style>